<template>
    <div>
        <div class="user-container">
            <el-card class="user-profile" shadow="hover" :body-style="{ padding: '0px' }">
                <div class="user-profile-bg"></div>
                <div class="user-avatar-wrap">
                    <el-avatar class="user-avatar" :size="120" :src="avatarImg" />
                </div>
                <div class="user-info">
                    <w-card>
                        <h2>个人信息</h2>
                        <div class="profile-field">
                            <label>姓名：</label>
                            <p>{{ studentForm.studentName }}</p>
                        </div>
                        <div class="profile-field">
                            <label>性别：</label>
                            <p>{{ studentForm.studentSex }}</p>
                        </div>
                        <div class="profile-field">
                            <label>年龄：</label>
                            <p>{{ studentForm.studentAge }}</p>
                        </div>
                        <div class="profile-field">
                            <label>电话：</label>
                            <p>{{ studentForm.studentPhone }}</p>
                        </div>
                        <div class="info-icon">
                            <a href="https://github.com/lin-xin" target="_blank"> <i
                                    class="el-icon-lx-github-fill"></i></a>
                            <i class="el-icon-lx-qq-fill"></i>
                            <i class="el-icon-lx-facebook-fill"></i>
                            <i class="el-icon-lx-twitter-fill"></i>
                        </div>
                    </w-card>
                </div>
            </el-card>
            <el-card class="user-content" shadow="hover"
                :body-style="{ padding: '20px 50px', height: '100%', boxSizing: 'border-box' }">
                <el-tabs tab-position="left" v-model="activeName">
                    <el-tab-pane name="label1" label="编辑信息" class="user-tabpane">
                        <el-form ref="formRef" :rules="rules" :model="studentForm" label-width="120px"
                            label-position="left">
                            <el-row :gutter="50">
                                <el-col :span="20">
                                    <el-form-item label="姓名" prop="studentForm.studentName">
                                        <el-input v-model="studentForm.studentName"></el-input>
                                    </el-form-item>
                                    <el-form-item label="年龄" prop="studentForm.studentAge">
                                        <el-input-number v-model="studentForm.studentAge" :min="18" :max="100" />
                                    </el-form-item>
                                    <el-form-item label="性别" prop="studentForm.studentSex">
                                        <el-select v-model="studentForm.studentSex" placeholder="请选择">
                                            <el-option key="男" label="男" value="男"></el-option>
                                            <el-option key="女" label="女" value="女"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="电话号码" prop="studentForm.studentPhone">
                                        <el-input v-model="studentForm.studentPhone"></el-input>
                                    </el-form-item>
                                    <el-form-item label="身份证" prop="studentForm.studentIdentityId">
                                        <el-input v-model="studentForm.studentIdentityId"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-col :span="24">
                                <el-form-item>
                                    <el-button type="primary" @click="onSubmit(formRef)">提交修改</el-button>
                                    <el-button @click="onReset(formRef)">重置信息</el-button>
                                </el-form-item>
                            </el-col>
                        </el-form>

                    </el-tab-pane>
                    <el-tab-pane name="label2" label="我的头像" class="user-tabpane">
                        <div class="crop-wrap" v-if="activeName === 'label2'">
                            <vueCropper ref="cropper" :img="imgSrc" :autoCrop="true" :centerBox="true" :full="true"
                                mode="contain">
                            </vueCropper>
                        </div>
                        <el-button class="crop-demo-btn" type="primary">选择图片
                            <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
                        </el-button>
                        <el-button type="success" @click="saveAvatar">上传并保存</el-button>
                    </el-tab-pane>
                    <el-tab-pane name="label3" label="修改密码" class="user-tabpane">
                        <el-form class="w500" label-position="top">
                            <el-form-item label="旧密码：">
                                <el-input type="password" v-model="form.old"></el-input>
                            </el-form-item>
                            <el-form-item label="新密码：">
                                <el-input type="password" v-model="form.new"></el-input>
                            </el-form-item>
                            <el-form-item label="确认新密码：">
                                <el-input type="password" v-model="form.new1"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="changePassword">保存</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts" name="ucenter">
import { onMounted, reactive, ref } from 'vue';
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';
import avatar from '@/assets/img/img.jpg';
import TabsComp from '../element/tabs.vue';

import * as studentApi from '@/api/student';
import * as accountApi from '@/api/account';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import router from '@/router';


const rules: FormRules = {
    "student.studentPhone": [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
    "student.studentSex": [{ required: true, message: '请选择性别', trigger: 'blur' }],
    'student.studentAge': [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    "student.studentName": [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    "student.studentIdentityId": [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
};
// 定义初始的空对象
const initialStudentData: studentApi.studentItemData = {
    studentId: 0,
    studentName: '',
    studentIdentityId: '',
    studentSex: '男',
    studentAge: 18,
    studentPhone: ''
};

const formRef = ref<FormInstance>();
// 初始化 studentForm 为初始的空对象
const studentForm = ref<studentApi.studentItemData>({ ...initialStudentData });

const initStudentForm = () => {
    const storedStudentInfo = localStorage.getItem("studentInfo");
    if ((JSON.parse(storedStudentInfo).studentId) != null) {
        studentApi.getStudentByStudentId(JSON.parse(storedStudentInfo).studentId).then((resp) => {
            studentForm.value = resp.data.data.getStudentByStudentId;
            ElMessage.success('获取信息成功！');
            console.log(resp);
        }).catch((resp) => {
            ElMessage.warning('获取信息失败！');
            console.log(resp)
        })
    } else {
        ElMessage.warning('还未完善个人信息！');
    }
}
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
    // 表单校验
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            studentApi.updateStudent(studentForm.value).then((resp) => {
                ElMessage.success('报名表提交成功！');
                console.log(resp);
            }).catch((resp) => {
                ElMessage.warning('报名表提交失败！');
                console.log(resp)
            })
        } else {
            return false;
        }
    });
};
// 重置
const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};
const name = localStorage.getItem('vuems_name');
const form = reactive({
    new1: '',
    new: '',
    old: '',
});
const changePassword = async () => {
    if (form.new !== form.new1) {
        ElMessage.error('两次新密码不一致');
        return;
    }
    
    console.log(localStorage.getItem('studentAccountId'));       
    const response = await accountApi.changePassword(name,localStorage.getItem('studentAccountId'),form.old,form.new);
    if (response.status == 200) {
        ElMessage.success('修改密码成功，请重新登陆');
        localStorage.removeItem('vuems_name');
        localStorage.removeItem('accountId');
        router.push('/login');
    }
    console.log(response);
}

const activeName = ref('label1');

const avatarImg = ref(avatar);
const imgSrc = ref(avatar);
const cropImg = ref('');
const cropper: any = ref();

const setImage = (e: any) => {
    const file = e.target.files[0];
    if (!file.type.includes('image/')) {
        return;
    }
    const reader = new FileReader();
    reader.onload = (event: any) => {
        imgSrc.value = event.target.result;
        cropper.value && cropper.value.replace(event.target.result);
    };
    reader.readAsDataURL(file);
};

const cropImage = () => {
    cropImg.value = cropper.value?.getCroppedCanvas().toDataURL();
};

const saveAvatar = () => {
    avatarImg.value = cropImg.value;
};

onMounted(() => {
    initStudentForm();
});
</script>

<style scoped>
.user-container {
    display: flex;
}

.user-profile {
    position: relative;
}

.user-profile-bg {
    width: 100%;
    height: 200px;
    background-image: url('../../assets/img/ucenter-bg.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.user-profile {
    width: 500px;
    margin-right: 20px;
    flex: 0 0 auto;
    align-self: flex-start;
}

.user-avatar-wrap {
    position: absolute;
    top: 135px;
    width: 100%;
    text-align: center;
}

.user-avatar {
    border: 5px solid #fff;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 7px 12px 0 rgba(62, 57, 107, 0.16);
}

.user-info {
    text-align: center;
    padding: 80px 0 30px;
}

.info-name {
    margin: 0 0 20px;
    font-size: 22px;
    font-weight: 500;
    color: #373a3c;
}

.info-desc {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;
}

.info-desc,
.info-desc a {
    font-size: 18px;
    color: #55595c;
}

.info-icon {
    margin-top: 10px;
}

.info-icon i {
    font-size: 30px;
    margin: 0 10px;
    color: #343434;
}

.user-content {
    flex: 1;
}

.user-tabpane {
    padding: 10px 20px;
}

.crop-wrap {
    width: 600px;
    height: 350px;
    margin-bottom: 20px;
}

.crop-demo-btn {
    position: relative;
}

.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}

.w500 {
    width: 500px;
}

.user-footer {
    display: flex;
    border-top: 1px solid rgba(83, 70, 134, 0.1);
}

.user-footer-item {
    padding: 20px 0;
    width: 33.3333333333%;
    text-align: center;
}

.user-footer>div+div {
    border-left: 1px solid rgba(83, 70, 134, 0.1);
}
</style>

<style>
.el-tabs.el-tabs--left {
    height: 100%;
}
</style>
<style>
.profile {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
}

.profile-field {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}
</style>
